package com.meitianhui.convenitenbuy.main.ui;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.RequestOptions;
import com.bumptech.glide.signature.ObjectKey;
import com.meitianhui.convenitenbuy.App;
import com.meitianhui.convenitenbuy.Constants;
import com.meitianhui.convenitenbuy.R;
import com.meitianhui.convenitenbuy.base.BaseActivity;
import com.meitianhui.convenitenbuy.config.InfoProvider;
import com.meitianhui.convenitenbuy.main.contract.LoginContract;
import com.meitianhui.convenitenbuy.main.di.DaggerMainComponent;
import com.meitianhui.convenitenbuy.main.di.MainModule;
import com.meitianhui.convenitenbuy.main.model.bean.AppToken;
import com.meitianhui.convenitenbuy.main.model.bean.EventBean;
import com.meitianhui.convenitenbuy.main.model.bean.HyphenateInfo;
import com.meitianhui.convenitenbuy.main.model.bean.UserToken;
import com.meitianhui.convenitenbuy.main.model.bean.VerifyPhone;
import com.meitianhui.convenitenbuy.main.presenter.LoginPresenter;
import com.meitianhui.convenitenbuy.module.mine.model.ConsumerInfo;
import com.meitianhui.convenitenbuy.module.mine.model.UserAsset;
import com.meitianhui.convenitenbuy.module.mine.model.UserInfo;
import com.meitianhui.convenitenbuy.util.EmptyUtil;
import com.meitianhui.convenitenbuy.util.JumpUtil;
import com.meitianhui.convenitenbuy.util.PreferenceUtils;
import com.meitianhui.convenitenbuy.util.RxBus;
import com.meitianhui.convenitenbuy.util.RxUtils;
import com.meitianhui.convenitenbuy.util.StringUtils;
import com.meitianhui.convenitenbuy.util.TipUtils;
import com.meitianhui.convenitenbuy.widget.dialog.LoadingDialog;

import java.util.HashMap;

import javax.inject.Inject;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

/**
 * 登录页面
 */

public class LoginActivity extends BaseActivity implements LoginContract.View {
    private EditText mEtPhone,mEtCode;
    private TextView mTvCode;
    private RelativeLayout rlImgCodeBox;
    private EditText etImgCode;
    private ImageView ivImgCode;
    private CheckBox mCbChoose;
    private String mPhone;
    private String imageCode;
    private TextView mTvTime;
    private String flag;
    public static boolean mIsShow = false;
    private LoadingDialog mDialog;
    @Inject
    LoginPresenter presenter;

    @Override
    protected void initView(Bundle savedInstanceState) {
        setContentView(R.layout.activity_login);
        DaggerMainComponent.builder()
                .appComponent(App.getInstance().getAppComponent())
                .mainModule(new MainModule(this))
                .build()
                .inject(this);
        RxUtils.bindEvents(getViewById(R.id.iv_close), this);
        RxUtils.bindEvents(getViewById(R.id.btn_login),this);
        RxUtils.bindEvents(getViewById(R.id.tv_agreement),this);
        mCbChoose = getViewById(R.id.cb_choose);
        mEtPhone = getViewById(R.id.et_phone);
        mTvCode = getViewById(R.id.tv_code);
        mEtCode = getViewById(R.id.et_code);
        mTvTime = getViewById(R.id.tv_time);
        rlImgCodeBox = getViewById(R.id.rl_login_img_code);
        etImgCode = getViewById(R.id.et_login_img_code);
        ivImgCode = getViewById(R.id.iv_login_img_code);
        RxUtils.bindEvents(ivImgCode, this);
        RxUtils.bindEvents(mTvCode, this);
        flag = getIntent().getStringExtra(JumpUtil.INTENT_VALUE);
        // 给验证码的输入增加状态监听器。
        addListenerOnInput(this);
    }

    private void addListenerOnInput(final Context context) {
        etImgCode.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                String text = s.toString();
                if (text.length() == 4) {
                    // 自动进行获取验证码操作
                    imageCode = text;
                    mPhone = mEtPhone.getText().toString();
                    if (!StringUtils.isPhone(mPhone)) {
                        TipUtils.showToast(App.getInstance(), "请输入正确的手机号码");
                        return;
                    }
                    mDialog = new LoadingDialog(context);
                    if (TextUtils.isEmpty(InfoProvider.getAppToken(App.getInstance()))) {
                        presenter.getAppToken();
                    } else {
                        presenter.verifyPhone(mPhone);
                    }
                }
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        mIsShow = true;
    }

    @Override
    protected void onPause() {
        super.onPause();
        mIsShow = false;
    }

    @Override
    public void call(View v) {
        super.call(v);
        switch (v.getId()) {
            case R.id.iv_close:   //关闭的图片
                Intent i = new Intent();
                i.putExtra(JumpUtil.INTENT_VALUE, "");
                setResult(RESULT_OK, i);
                this.finish();
                break;

            case R.id.tv_code:   //获取验证码
                mPhone = mEtPhone.getText().toString();
                if (!StringUtils.isPhone(mPhone)) {
                    TipUtils.showToast(App.getInstance(), "请输入正确的手机号码");
                    break;
                }
                if (rlImgCodeBox.getVisibility() == View.VISIBLE) {
                    imageCode = etImgCode.getText().toString();
                    if (EmptyUtil.isEmpty(imageCode) || imageCode.length() < 4) {
                        TipUtils.showToastLong(this, "请输入图片识别码");
                        break;
                    }
                }
                mDialog = new LoadingDialog(this);
                if (TextUtils.isEmpty(InfoProvider.getAppToken(App.getInstance()))) {
                    presenter.getAppToken();
                } else {
                    presenter.verifyPhone(mPhone);
                }
                break;

            case R.id.iv_login_img_code:
                mPhone = mEtPhone.getText().toString();
                if (!StringUtils.isPhone(mPhone)) {
                    TipUtils.showToast(App.getInstance(), "请输入正确的手机号码");
                    break;
                }
                refreshImageCode();
                break;

            case R.id.tv_agreement:  //用户协议
                startActivity(new Intent(this,UserAgreementActivity.class));
                break;

            case R.id.btn_login:  //登录
                String code = mEtCode.getText().toString();
                mPhone = mEtPhone.getText().toString();
                if (!mCbChoose.isChecked()) {
                    TipUtils.showToast(App.getInstance(),"请确认阅读每天惠用户协议");
                    return;
                }
                if(TextUtils.isEmpty(mPhone)){
                    TipUtils.showToast(App.getInstance(),"手机号不能为空");
                    return;
                }
                if(!StringUtils.isPhone(mPhone)){
                    TipUtils.showToast(App.getInstance(),"请输入正确的手机号码");
                    return;
                }
                if(TextUtils.isEmpty(code)){
                    TipUtils.showToast(App.getInstance(),"验证码不能为空");
                    return;
                }
                mDialog = new LoadingDialog(this);
                presenter.login(mPhone,code);
                break;
        }
    }

    @Override
    public void getAppTokenSuccess(AppToken appToken) {
        PreferenceUtils.putString(this, Constants.APP_TOKEN_KEY,appToken.getApp_token());
        PreferenceUtils.putString(this, Constants.APP_SECURITY_CODE,appToken.getSecurity_code());
        presenter.verifyPhone(mPhone);
    }

    /**
     * 验证电话号码成功
     * @param verifyPhone
     */
    @Override
    public void verifyPhoneSuccess(VerifyPhone verifyPhone) {
        presenter.getPhoneCodeMsg();
    }

    /**
     * 成功发送电话并返回唯一标识去请求发送拿到验证码
     */
    @Override
    public void phoneCodeMsgSuccess(String code) {
        presenter.getPhoneCode(mPhone, code, imageCode);
    }

    private void refreshImageCode() {
        String url = "https://appportal.meitianhui.com/ops-notification/imageCode/sendImageCode?mobile=" + mPhone;
        // 禁用 Glide 缓存
        Glide.with(this)
                .load(url)
                .apply(new RequestOptions()
                        .placeholder(R.mipmap.icon_default_picture)
                        .error(R.mipmap.icon_default_picture)
                        .diskCacheStrategy(DiskCacheStrategy.NONE)
                        .skipMemoryCache(true)
                        .signature(new ObjectKey(String.valueOf(System.currentTimeMillis()))))
                .into(ivImgCode);
    }

    /**
     * 成功发送验证码
     * @param msg
     */
    @Override
    public void phoneCodeSuccess(String msg) {
        if (mDialog != null) {
            mDialog.stopProgressDialog();
        }
        mTvCode.setVisibility(View.GONE);
        mTvTime.setVisibility(View.VISIBLE);
        timer.start();
    }

    /**
     * 请求验证码失败，需要用户去输入图片识别码。
     * @param msg error msg
     */
    @Override
    public void phoneCodeFailed(String msg) {
        if (mDialog != null) {
            mDialog.stopProgressDialog();
        }

        rlImgCodeBox.setVisibility(View.VISIBLE);
        etImgCode.setText("");
        etImgCode.setFocusable(true);
        etImgCode.requestFocus();
        TipUtils.showToastLong(this, msg);
        refreshImageCode();
    }

    /**
     * 拿到用户的token
     * @param userToken
     */
    @Override
    public void loginSuccess(UserToken userToken) {
        if(userToken==null){
            TipUtils.showToast(App.getInstance(),"登录失败");
            return;
        }
        PreferenceUtils.saveObject(this,Constants.USER_TOKEN,userToken);
        presenter.getUserInfo();
    }
    /**
     * 拿到用户的信息
     * @param userInfo
     */
    @Override
    public void getUserInfoSuccess(UserInfo userInfo) {
        if(userInfo==null){
            TipUtils.showToast(App.getInstance(),"登录失败");
            return;
        }
        PreferenceUtils.saveObject(App.getInstance(),Constants.USER_INFO,userInfo);
        presenter.getConsumerInfo();
    }
    /**
     * 消费者信息
     * @param consumerInfo
     */
    @Override
    public void getConsumerInfoSuccess(ConsumerInfo consumerInfo) {
        if(consumerInfo==null){
            TipUtils.showToast(App.getInstance(),"登录失败");
            return;
        }
        PreferenceUtils.saveObject(this,Constants.CONSUMER_INFO,consumerInfo);
        HashMap<String, String> doc_url = consumerInfo.getDoc_url();
        String headImg = "";
        if (doc_url != null) {
            headImg = doc_url.get(consumerInfo.getHead_pic_path());
        }
        presenter.getHyphenateInfo(consumerInfo.getNick_name(),headImg);

    }

    /**
     * 获取环信的信息
     * @param hyphenateInfo
     */
    @Override
    public void getHyphenateSuccess(HyphenateInfo hyphenateInfo) {
        if(hyphenateInfo==null){
            TipUtils.showToast(App.getInstance(),"登录失败");
            return;
        }
        PreferenceUtils.saveObject(this,Constants.HYPHENATE_INFO,hyphenateInfo);
        presenter.loginHyphenate(hyphenateInfo.getIm_user_id());
        presenter.getUserAsset();
    }

    /**
     * 用户资产
     * @param userAsset
     */
    @Override
    public void getUserAssetSuccess(UserAsset userAsset) {
        if(userAsset==null){
            TipUtils.showToast(App.getInstance(),"登录失败");
            return;
        }
        PreferenceUtils.saveObject(this,Constants.USER_ASSET,userAsset);
        presenter.postPushInfo();
    }


    @Override
    public void postPushInfoSuccess() {
        mDialog.stopProgressDialog();
        PreferenceUtils.putInt(this, Constants.LOGIN_STATUS,1);
        RxBus.get().post(new EventBean(Constants.EVENT_TYPE_LOGIN_SUCCESS));
        Intent intent = new Intent();
        intent.putExtra(JumpUtil.INTENT_VALUE, flag);//辨别跳转
        setResult(RESULT_OK, intent);
        finish();
    }

    @Override
    public void onFail(int code, String msg) {
        if(mDialog!=null){
            mDialog.stopProgressDialog();
        }

        Observable.create(new ObservableOnSubscribe<String>() { // 第一步：初始化Observable
            @Override
            public void subscribe(@NonNull ObservableEmitter<String> e) throws Exception {
                e.onNext(msg);
            }
        }).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread()).subscribe(new Consumer<String>() {
            @Override
            public void accept(String integer) throws Exception {

               // TipUtils.showToast(App.getInstance(),msg);
            }
        });
    }

    @Override
    public void loginFail(String msg) {
        if(mDialog!=null){
            mDialog.stopProgressDialog();
        }
        TipUtils.showToast(this,msg);
    }


    @Override
    public void showError(String msg) {

    }

    private CountDownTimer timer = new CountDownTimer(120000, 1000) {
        @Override
        public void onTick(long millisUntilFinished) {
            mTvTime.setText("(" + millisUntilFinished / 1000 + "s)");
        }

        @Override
        public void onFinish() {
            mTvCode.setVisibility(View.VISIBLE);
            mTvTime.setVisibility(View.GONE);
        }
    };
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        // TODO Auto-generated method stub
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
            Intent i = new Intent();
            i.putExtra(JumpUtil.INTENT_VALUE, "");
            setResult(RESULT_OK, i);
            this.finish();
        }
        return false;
    }


}
